package com.cjr.ddp.controller;

import com.cjr.ddp.entity.User;
import com.cjr.ddp.service.UserService;
import com.cjr.ddp.util.MyTools;
import com.cjr.ddp.util.ReturnMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author cjr
 * @date Created in 2020-03-05 20:56
 * @description
 * @modified By
 */
@RestController
@RequestMapping("/user")
public class UserLoginController {

    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * @param user
     * @return java.lang.Object
     * @throws
     * @author cjr
     * @date 2020-03-05 21:09
     * @description 用户登录
     */
    @RequestMapping("/login")

    public Object login(User user) {

        ReturnMsg returnMsg = new ReturnMsg();
        //初始化Redis
        ValueOperations<String, ReturnMsg> operations = redisTemplate.opsForValue();
        //密码MD5加密
        String MD5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(MD5Password);
        //System.out.println(MD5Password);
        //查询用户
        User userBack = userService.selectUserByLoginInfo(user);
        //判断用户是否存在且有效
        if (userBack == null) {
            returnMsg.setMsg("账号或密码错误，请重新登录！");
            returnMsg.setSuccess(false);
        } else if (userBack.getStatus() == 0) {
            returnMsg.setMsg("该用户已被删除！");
            returnMsg.setSuccess(false);
        } else {
            String token = MyTools.getUUID();
            returnMsg.setMsg("登录成功！");
            returnMsg.setCode("200");
            returnMsg.setSuccess(true);
            returnMsg.setObject(userBack);
            returnMsg.setToken(token);
            //将token和用户信息存入redis服务器
            operations.set(token, returnMsg, 1, TimeUnit.HOURS);
        }
        return returnMsg;
    }

    /**
     * @param
     * @return com.cjr.ddp.util.ReturnMsg
     * @throws
     * @author cjr
     * @date 2020-03-08 18:12
     * @description 用户退出登录
     */
    @RequestMapping("/loginOut")
    public ReturnMsg loginOut(String token) {
        ReturnMsg returnMsg = new ReturnMsg();
        boolean deleteToken = redisTemplate.delete(token);
        if (deleteToken == true) {
            returnMsg.setToken("");
            returnMsg.setSuccess(true);
            returnMsg.setCode("200");
            returnMsg.setMsg("退出成功！");
        }
        return returnMsg;
    }

}
